<template>
  <div class="roleBox bg-f2">
    <div class="bg-f2 bg-fff" style="padding-bottom: 45px">
      <el-breadcrumb separator-class="el-icon-arrow-right" class="addHead pAll">
        <el-breadcrumb-item :to="{ path: '/roleManage' }">角色管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ title }}</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- <div style="position: absolute; left: -15px; width: 100%; height: 1px; background: #e5e5e5"></div> -->
      <el-form ref="addRoleForm" class="pAll" style="padding-bottom: 60px !important" :style="{ minHeight: transferHeight.contentH + 'px' }" :rules="addRoleRules" :model="addRole" label-width="80px">
        <el-form-item label="角色名称:" prop="roleName" class="roleName">
          <el-input :maxlength="12" v-model.trim="addRole.roleName" clearable placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述:" class="roleName">
          <el-input type="textarea" resize="none" show-word-limit :rows="5" :maxlength="100" placeholder="角色描述" v-model.trim="addRole.describe"></el-input>
        </el-form-item>
        <el-form-item label="分配权限:" class="distribute">
          <el-tabs v-model="activeRoleName" type="card" @tab-click="handleClick">
            <el-tab-pane :label="item.qxmc" :name="item.qxmc" v-for="item in roleList" :key="item.id">
              <el-checkbox :indeterminate="isIndeterminate" @change="ischeckeds(item, $event)" v-model="checkAll" style="margin-right: 15px">全选</el-checkbox>
              <el-collapse :accordion="true" @change="collapseChange">
                <el-checkbox-group v-model="checkList" @change="checkeds(item)">
                  <el-collapse-item v-for="item2 in item.children" :key="item2.id" :name="item2.id">
                    <template slot="title">
                      <el-checkbox :label="item2.id" @change="ss(item2.id, item.id, $event)">{{ item2.qxmc }}</el-checkbox>
                    </template>
                    <div class="checkItem">
                      <el-checkbox v-for="item3 in item2.children" :label="item3.id" :key="item3.id" @change="checkedItem(item, item2, item3, $event)" class="checkbox_item">
                        {{ item3.qxmc }}
                        <el-tooltip content="选择四级按钮权限" placement="right-start" effect="light" v-if="item3.children === null || item3.children.length > 0 ? true : false">
                          <span @click.prevent="haha(item, item2, item3, $event)">
                            <i :class="[iconBtn]" :id="'sBtn' + item3.id" style="margin-left: 5px; font-size: 16px" ref="SJBTN"></i>
                          </span>
                        </el-tooltip>
                      </el-checkbox>
                      <!-- v-show="item2.qxmc === '工单管理' ? true : false" -->
                      <div class="checkbox_item2" v-if="showSJ">
                        <el-checkbox v-for="btn in sijiList[2].children" :label="btn.id" :key="btn.id" @change="checkedItem2(sijiList[0], sijiList[1], sijiList[2], $event)">{{
                          btn.qxmc
                        }}</el-checkbox>
                      </div>
                    </div>
                  </el-collapse-item>
                </el-checkbox-group>
              </el-collapse>
            </el-tab-pane>
          </el-tabs>
          <div class="fooer_box bg-fff">
            <!-- <el-button @click="addRoleSubmit">保存并新增</el-button> -->
            <div style="width: 150px; margin: 0 auto">
              <el-button @click="gotolink" v-preventReClick class="btnSizeStyle">取消</el-button>
              <el-button @click="handleNodeClick('addRoleForm', title)" type="primary" v-preventReClick class="btnSizeStyle">保存</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getUrl, setUrl, removeUrl } from '../../utils/getUrl.js'
import { pinT } from '../../utils/allUrl.js'
import { twoLevelH } from '@/assets/js/calcHeight'

export default {
  data: function () {
    return {
      addRole: {
        roleName: '', // 角色名称
        describe: '', // 角色描述
      },
      activeRoleName: '运维概况', // 默认值
      addRoleRules: {
        roleName: [
          { required: true, message: '输入角色名称', trigger: 'blur' },
          { min: 1, max: 12, message: '长度在 1 到 12 个字符', trigger: 'blur' },
        ],
      },
      title: '', // 编辑新增标题
      xiuId: '', // 编辑角色ID
      roleList: [], // 角色数据源
      checkList: [], // 选中角色的id数组
      checkAll: false, // 全选按钮
      checkbox: [], // 提交数组
      nansou: [], // 勾选框
      sijiList: [], // 四级权限
      iconBtn: 'el-icon-arrow-right',
      showSJ: false, // 显示和隐藏四级权限
      // dianjiShow: true,
      isIndeterminate: false,
      // isIndeterminateNum: []
    }
  },
  created: function () {
    this.getroleList()
    // 判断新增/修改
    const { title, id, jsmc, jsms } = this.$route.query
    if (id) {
      this.xiuId = id
      this.addRole.roleName = jsmc
      this.addRole.describe = jsms
      this.getQuanXian(id)
    }
    this.title = title
  },
  computed: {
    transferHeight: function () {
      // 计算屏幕滚动高度 - nav - 导航栏
      return {
        contentH: window.innerHeight - twoLevelH,
        pb: twoLevelH,
      }
    },
  },
  methods: {
    gotolink() {
      this.$router.replace('/roleManage')
    },
    // 展开四级权限
    haha(val, val2, val3, e) {
      this.$refs.SJBTN.forEach((item) => {
        if (item.id === 'sBtn' + val3.id) {
          if (item.className === 'el-icon-arrow-right') {
            item.className = 'el-icon-arrow-down'
            this.sijiList.push(val, val2, val3)
            this.showSJ = true
            // this.dianjiShow = false
          } else {
            item.className = 'el-icon-arrow-right'
            this.sijiList = []
            return (this.showSJ = false)
            // this.dianjiShow = true
          }
        } else {
          if (item.className === 'el-icon-arrow-down') {
            this.sijiList = []
            this.showSJ = false
          }
          item.className = 'el-icon-arrow-right'
          this.sijiList.push(val, val2, val3)
          this.showSJ = true
        }
      })
      if (e.target.className === 'el-icon-arrow-right') {
        this.sijiList = []
        return (this.showSJ = false)
      }
    },
    // 角色数据源
    async getroleList() {
      const { data: res } = await this.$http.post(`${pinT}quanXian/selectQuanXian`)
      this.roleList = res.data.list
    },
    // 编辑时选中状态
    async getQuanXian(id) {
      const params = new URLSearchParams()
      params.append('JS_ID', id)
      const { data: res } = await this.$http.post(`${pinT}quanXian/selectMenu`, params)
      this.checkList = res.data || []
      setUrl('soletag', JSON.stringify(this.checkList))
    },
    // addRoleSubmit: function() {
    //   console.log('oK')
    // },
    // 提交角色按钮
    handleNodeClick(addRoleForm, title) {
      const { roleName, describe } = this.addRole
      const s2 = new Set(this.checkbox)
      const deleteAll2 = [...s2]
      let checkbox = deleteAll2
      if (checkbox.length === 1) {
        checkbox = []
      }
      const userId = JSON.parse(getUrl('userconter')).id
      this.$refs.addRoleForm.validate(async (valid) => {
        if (valid) {
          if (title === '新增角色') {
            const params = new URLSearchParams()
            params.append('JSMC', roleName)
            params.append('JSMS', describe)
            params.append('ids', checkbox)
            params.append('YH_ID', userId)
            const { data: res } = await this.$http.post(`${pinT}juese/insertJueSe`, params)
            if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.$router.push('/roleManage')
          } else {
            let checkbox2 = []
            if (this.checkbox.length === 0) {
              checkbox2 = this.checkList
            } else {
              checkbox2 = this.checkbox
            }
            const s1 = new Set(checkbox2)
            const deleteAll = [...s1]
            const params = new URLSearchParams()
            params.append('JSMC', roleName)
            params.append('JSMS', describe)
            params.append('ids', deleteAll)
            params.append('YH_ID', userId)
            params.append('ID', this.xiuId)
            const { data: res } = await this.$http.post(`${pinT}juese/updateJueSe`, params)
            if (res.code === '0014') {
              return ''
            } else if (res.code !== '0000') {
              return this.$message({
                type: 'error',
                message: res.message,
                center: true,
              })
            }
            this.$message({
              type: 'success',
              message: res.message,
              center: true,
            })
            this.$router.push('/roleManage')
          }
        } else {
          this.$message({
            type: 'error',
            message: '请填写正确的信息',
            center: true,
          })
          return false
        }
      })
    },
    // 角色tab栏切换
    handleClick(tab) {
      this.checkbox = JSON.parse(getUrl('soletag')) || []
      this.checkList = this.checkbox
      const arr = this.roleList[tab.index].children
      const arrItem = []
      arrItem.push(this.roleList[tab.index].id)
      arr.forEach((item) => {
        arrItem.push(item.id)
        item.children.forEach((item2) => {
          arrItem.push(item2.id)
          if (item2.children.length !== 0) {
            item2.children.forEach((item3) => {
              arrItem.push(item3.id)
            })
          }
        })
      })
      let isoks = ''
      arrItem.forEach((val) => {
        isoks = this.checkbox.includes(val)
      })
      if (isoks) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
      // this.isIndeterminateNum = arrItem // 判断确定状态
      this.showSJ = false
      this.sijiList = []
      this.iconBtn = 'el-icon-arrow-right'
      this.$refs.SJBTN.forEach((item) => {
        item.className = 'el-icon-arrow-right'
      })
    },
    // 复选框组
    checkeds(val) {
      const num = []
      const arr = []
      num.push(val.id)
      arr.push(val.id)
      val.children.forEach((item) => {
        num.push(item.id)
        arr.push(item.id)
        item.children.forEach((item2) => {
          num.push(item2.id)
          arr.push(item2.id)
          item2.children.forEach((item3) => {
            num.push(item3.id)
          })
        })
      })
      // this.checkAll = num.length === this.checkbox.length
      this.checkAll = this.isContained(this.checkList, num)
      // if (this.checkList.length > this.isIndeterminateNum.length) {
      //   this.checkAll ? (this.isIndeterminate = false) : (this.isIndeterminate = true)
      // } else {
      //   console.log((this.isIndeterminate = this.checkList.length > 1 && this.checkList.length < this.isIndeterminateNum.length))
      // }

      // if (arr.sort((a, b) => a - b).join(',') === this.checkbox.sort((a, b) => a - b).join(',')) {
      //   this.checkList = []
      // }
      setUrl('soletag', JSON.stringify(this.checkbox)) // 不知道什么用
    },
    // 计算是否为全选状态
    isContained(a, b) {
      if (!(a instanceof Array) || !(b instanceof Array)) return false
      if (a.length < b.length) return false
      var aStr = a.toString()
      for (var i = 0, len = b.length; i < len; i++) {
        if (aStr.indexOf(b[i]) === -1) return false
      }
      return true
    },
    // 全选按钮
    ischeckeds(val, e) {
      const arrs = JSON.parse(getUrl('soletag')) || []
      const arr = []
      if (e) {
        arr.push(val.id)
        val.children.forEach((item) => {
          arr.push(item.id)
          item.children.forEach((item2) => {
            arr.push(item2.id)
            item2.children.forEach((item3) => {
              arr.push(item3.id)
            })
          })
        })
        this.checkList = [...arrs, ...arr]
        const s1 = new Set(this.checkList)
        const deleteAll = [...s1]
        this.checkList = deleteAll
      } else {
        arr.push(val.id)
        val.children.forEach((item) => {
          arr.push(item.id)
          item.children.forEach((item2) => {
            arr.push(item2.id)
            item2.children.forEach((item3) => {
              arr.push(item3.id)
            })
          })
        })
        arr.forEach((item) => {
          const deletes = arrs.findIndex((item2, index) => item2 === item)
          arrs.splice(deletes, 1)
        })
        this.checkList = arrs
      }
      // this.checkList = [...arrs, ...arr]
      // const s1 = new Set(this.checkList)
      // const deleteAll = [...s1]
      // if (!this.checkAll) {
      //   arr.forEach(item => {
      //     const deletes = deleteAll.findIndex((item2, index) => item2 === item)
      //     deleteAll.splice(deletes, 1)
      //   })
      // }
      // this.checkList = this.checkAll ? this.checkList : []
      // this.checkAll ? (this.isIndeterminate = false) : (this.isIndeterminate = true)
      // this.checkList = deleteAll
      this.checkbox = this.checkList
      setUrl('soletag', JSON.stringify(this.checkbox))
    },
    // 选中复选框
    ss(val, fuji, e) {
      if (e) {
        const arr = []
        this.roleList.forEach((item) => {
          item.children.forEach((item3) => {
            const ap = this.checkList.find((item4) => item4 === item3.id)
            if (ap) {
              this.checkList = [fuji, ...this.checkList]
              const s1 = new Set(this.checkList)
              this.checkList = [...s1]
              this.checkbox = this.checkList
              item3.children.forEach((item5) => {
                arr.push(item5.id)
                if (item5.children[0]) {
                  item5.children.forEach((item6) => {
                    arr.push(item6.id)
                    this.checkList = [...arr, ...this.checkList]
                    const s1 = new Set(this.checkList)
                    this.checkList = [...s1]
                    this.checkbox = this.checkList
                  })
                } else {
                  this.checkList = [...arr, ...this.checkList]
                  const s1 = new Set(this.checkList)
                  this.checkList = [...s1]
                  this.checkbox = this.checkList
                }
              })
            }
          })
        })
      } else {
        this.roleList.forEach((item) => {
          item.children.forEach((item3) => {
            if (item3.id === val) {
              item3.children.forEach((xs) => {
                const la = this.checkList.findIndex((ni) => ni === xs.id)
                this.checkList.splice(la, 1)
                this.checkbox = this.checkList
                xs.children.forEach((xss) => {
                  const la2 = this.checkList.findIndex((ni) => ni === xss.id)
                  this.checkList.splice(la2, 1)
                  this.checkbox = this.checkList
                })
              })
            }
          })
        })
        if (this.checkList.length === 1) {
          const la3 = this.checkList.findIndex((ni) => ni === fuji)
          this.checkList.splice(la3, 1)
          this.checkbox = this.checkList
        }
      }
    },
    // 四级权限选中状态
    checkedItem(val, val2, val3, e) {
      const arr = []
      const arr2 = []
      arr.push(val.id)
      arr.push(val2.id)
      // arr2.push(val2.id)
      // this.nansou.push(val.id)
      // this.nansou.push(val2.id)
      val3.children.forEach((item) => {
        arr.push(item.id)
        arr2.push(item.id)
        // this.nansou.push(item.id)
      })
      // const s3 = new Set(this.nansou)
      // const deleteAll22 = [...s3]
      this.checkList.push(...arr)
      const s2 = new Set(this.checkList)
      const deleteAll2 = [...s2]
      this.checkList = deleteAll2
      this.checkbox = this.checkList
      if (!e) {
        arr2.forEach((vals) => {
          const indexAll = this.checkbox.findIndex((indexs) => vals === indexs)
          if (indexAll !== -1) {
            this.checkbox.splice(indexAll, 1)
          }
        })

        // if (arr.sort((a, b) => a - b).join(',') === this.checkbox.sort((a, b) => a - b).join(',')) {
        //   this.checkList = []
        //   this.checkbox = []
        // }
        // if (deleteAll22.sort((a, b) => a - b).join(',') === this.checkbox.sort((a, b) => a - b).join(',')) {
        //   this.checkList = []
        //   this.checkbox = []
        // }
      }
    },
    // 四级权限选中状态2
    checkedItem2(val, val2, val3, e) {
      const arr = []
      arr.push(val.id)
      arr.push(val2.id)
      arr.push(val3.id)
      this.nansou.push(val.id)
      this.nansou.push(val2.id)
      this.nansou.push(val3.id)
      const s3 = new Set(this.nansou)
      const deleteAll22 = [...s3]
      this.checkList.push(...arr)
      const s2 = new Set(this.checkList)
      const deleteAll2 = [...s2]
      this.checkList = deleteAll2
      this.checkbox = this.checkList
      if (!e) {
        if (arr.sort((a, b) => a - b).join(',') === this.checkbox.sort((a, b) => a - b).join(',')) {
          this.checkList = []
          this.checkbox = []
        }
        if (deleteAll22.sort((a, b) => a - b).join(',') === this.checkbox.sort((a, b) => a - b).join(',')) {
          this.checkList = []
          this.checkbox = []
        }
      }
    },
    // 四级选项bug
    collapseChange(val) {
      this.sijiList = []
      this.showSJ = false
      this.iconBtn = 'el-icon-arrow-right'
      this.$refs.SJBTN.forEach((item) => {
        item.className = 'el-icon-arrow-right'
      })
    },
  },
  destroyed: function () {
    removeUrl('soletag')
  },
}
</script>
<style lang="scss" scoped>
.fooer_box {
  z-index: 100;
  .el-button {
    display: inline-block;
  }
}
::v-deep .el-tabs__nav-scroll {
  position: relative !important;
  z-index: 55;
  width: 100%;
}
::v-deep .el-tabs__nav-scroll::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background-color: #e4e7ed;
  z-index: 1;
}
::v-deep .el-tabs--card > .el-tabs__header {
  border-bottom: none !important;
}
// .el-breadcrumb {
//   height: 53px;
//   line-height: 53px;
//   // border-bottom: solid 1px #e5e5e5;
// }
.el-form {
  // margin: 30px 0;
  .roleName {
    width: 541px;
  }
  .el-tabs {
    width: 1400px;
    .el-collapse {
      border-left: 1px solid #e4e7ed;
      border-right: 1px solid #e4e7ed;
      .checkbox_item {
        margin-top: 10px;
        margin-left: 35px;
        // display: flex;
        // flex-wrap: wrap;
      }
      .checkbox_item2 {
        padding: 10px 60px 0 60px;
        // height: 40px;
        // line-height: 40px;
      }
    }
    .checkItem {
      margin: 0 15px;
    }
  }
  .fooer_box {
    position: fixed;
    bottom: 0;
    left: 182px;
    width: 100%;
    height: 56px;
    line-height: 56px;
    text-align: center;
    border-top: 1px solid #f4f4f4;
    box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.2);
  }
}

.el-form-item__label {
  line-height: 33px;
}
</style>
